const router = require('koa-router')()
const Image = require('../models/image')
const Sequelize = require("sequelize");
const mySequelize = require("../models/mySequelize")

router.prefix('/images')

// 随机返回一张图片
router.get('/randomOne', async (ctx, next)=>{
  let img = await Image.findOne({
      where:{
          outer_net: 0
      },
      order: [Sequelize.literal('rand()')]
  });
  ctx.body = JSON.stringify(img)
})

// 随机返回十张图片
router.get('/randomTen', async (ctx, next)=>{
    let imgList = await Image.findAll({
        where:{
            outer_net: 0
        },
        order: [Sequelize.literal('rand()')]
    });
    ctx.body = JSON.stringify(imgList.splice(0, 10));
})

// 随机返回96张图片
router.get('/random48', async (ctx, next)=>{
    let imgList = await Image.findAll({
        where:{
            outer_net: 0
        },
        order: [Sequelize.literal('rand()')]
    });
    ctx.body = JSON.stringify(imgList.splice(0, 48));
})


// 根据颜色返回相应的图片
router.get('/selectByColor', async (ctx, next)=>{
    let ctx_query = ctx.query;
    console.log(ctx.query);
    let sql = "SELECT * FROM img_table where colors like '%"+decodeURI(ctx_query['color']).replace(/23%/, "#")+"%' "
    let imgList = await mySequelize.query(sql, {
        model: Image,
        mapToModel: true // 如果你有任何映射字段,则在此处传递 true
    });
    ctx.body = JSON.stringify(imgList);
})

// 随机返回一张PC端背景图片
router.get('/randomBackground', async (ctx, next)=>{
    let sql = "SELECT * FROM img_table where size REGEXP '^[0-9]{4}×[0-9]{3}$' ORDER BY RAND() LIMIT 10"
    let imgList = await mySequelize.query(sql, {
        model: Image,
        mapToModel: true // 如果你有任何映射字段,则在此处传递 true
    });
    ctx.body = JSON.stringify(imgList);
})

// 按关键字模糊检索
router.get('/search', async (ctx, next)=>{
    let ctx_query = ctx.query;
    let sql = "SELECT * FROM img_table where tags like '%"+decodeURI(ctx_query['keyWord'])+"%' ORDER BY RAND()";
    if(/^23%[0-9|a-z|A-Z]{6}$/g.test(decodeURI(ctx_query['keyWord']))){
        sql = "SELECT * FROM img_table where colors like '%"+decodeURI(ctx_query['keyWord']).replace(/23%/, "#")+"%' ";
    }
    else if(/^\d+×\d+$/g.test(decodeURI(ctx_query['keyWord']))){
        sql = "SELECT * FROM img_table where size like '%"+decodeURI(ctx_query['keyWord'])+"%' ";
    }
    let imgList = await mySequelize.query(sql, {
        model: Image,
        mapToModel: true
    });
    ctx.body = JSON.stringify(imgList);
})

module.exports = router
